#include <head.h>
#define MAX_PROCESS (1)
int pipe_test_main(int argc, char *argv[])
{
    int pipefd[2];
    int i=0;

    // if (argc != 2)
    // {
    //     fprintf(stderr, "Usage: %s <string>\n", argv[0]);
    //     exit(EXIT_FAILURE);
    // }

    if (pipe(pipefd) == -1)
    {
        perror("pipe");
        exit(EXIT_FAILURE);
    }
    for(;i<MAX_PROCESS;i++){
        pid_t p =fork();
         if (p == -1)
        {
            perror("fork");
            exit(EXIT_FAILURE);
        }
        if(p == 0){
            break;
        }
    }

    if (i  == MAX_PROCESS)
    {                     
        close(pipefd[0]); /* Close unused read end */
        char buf[1024];

        for (size_t k = 0; k <4; k++)
        {
            CLEAR_ARRAY(buf);
            time_t t =time(NULL);
            strcpy(buf,ctime(&t));
            write(pipefd[1],buf,strlen(buf));
            sleep(1);   
        }
        close(pipefd[1]); /* Reader will see EOF */
        for(i=0;i<MAX_PROCESS;i++){
            wait(NULL);       
        }
        exit(EXIT_SUCCESS);
    }
    else
    {                   
        close(pipefd[1]); /* Close unused write end */
        char buf[1024];
        for (size_t k = 0; k < 10; k++)
        {
            CLEAR_ARRAY(buf);
            // printf("child before read\n");
            int len = read(pipefd[0],buf,sizeof(buf)-1);
            // printf("child after read\n");
            printf("[%d]read [%d]bytes:%s",i,len,buf);
            sleep(1);
            printf("sleep\n");
        }
        close(pipefd[0]);
        _exit(EXIT_SUCCESS);
    }
}
